package com.zzn.bookManage.controller;

import com.zzn.bookManage.pojo.Book;
import com.zzn.bookManage.pojo.User;
import com.zzn.bookManage.service.BookService;
import com.zzn.bookManage.util.ObjectHolder;
import com.zzn.bookManage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 删除图书信息
 */

@WebServlet("/deleteBook")
public class DeleteBook extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true); // 必定获得一个session
        User loginUser = (User) session.getAttribute("loginUser");
        boolean isAdmin = "admin".equals(loginUser.getUsername());

        int bid = 0;
        if (StringUtil.notBlank(req.getParameter("bid"))) bid = Integer.parseInt(req.getParameter("bid"));

        BookService bookService = ObjectHolder.getInstance().getBookService();

        Book in = new Book();
        in.setBid(bid);
        if (bookService.deleteBook(in)){
            // 删除成功
            req.setAttribute("msg","删除成功");
            if (isAdmin){
                resp.sendRedirect("/list?page=1");
            }else{
                req.setAttribute("msg","没有权限");
                req.getRequestDispatcher("/userMain.jsp").forward(req, resp);
            }
        }else{
            // 删除失败
            req.setAttribute("msg","删除失败");
            if (isAdmin){
                resp.sendRedirect("/list?page=1");
            }else{
                req.setAttribute("msg","没有权限");
                req.getRequestDispatcher("/userMain.jsp").forward(req, resp);
            }
        }
    }
}
